const Service = require('egg').Service;
var fs       = require('fs');
const common = require('../common/common')

const puppeteer = require('puppeteer');

class DidiTaixService extends Service {
    async doService(params) {
        let browser = null;
        let page = null;
        let text = null;
        if(!global.bowerauto || !global.bowerauto.browser){
            global.bowerauto = {};
            browser = await puppeteer.launch({
                headless: true,
                ignoreDefaultArgs: ["--enable-automation"]
              } );

            page = await browser.newPage();

            global.bowerauto.browser = browser;
            global.bowerauto.page = page;
        }else{
            browser = global.bowerauto.browser;
            page = global.bowerauto.page;
        }
        try{
          await page.goto('https://gsactivity.diditaxi.com.cn/gulfstream/activity/v2/giftpackage/index?g_channel='+params.channel+'&code='+ params.code);
        }catch(e){
          global.bowerauto = {};
          browser = await puppeteer.launch({
              headless: false,
              ignoreDefaultArgs: ["--enable-automation"]
            } );

          page = await browser.newPage();

          global.bowerauto.browser = browser;
          global.bowerauto.page = page;
        }
        await page.type('#main-phone',params.phone);
        page.click('#main-btn');
        await common.timeout(4000);
      
        let isSuccess = true;
        let element = await page.$("#receive-desc");
        if(element == null){
          isSuccess = false;
          element = await page.$("#error-title");
        }
        text = await page.evaluate(element => element.textContent, element);
        if(isSuccess && params.phone==text.split(" ")[1]){
          return {code:"00" ,msg: "充值成功"};
        }else{
          return {code:"01" ,msg: "充值失败"};
        }
    }
  }
  
  module.exports = DidiTaixService;